<template>
  <div class="upload-container">
    <el-upload
      class="image-uploader"
      :action="apiUrl"
      :file-list="fileList"
      :on-remove="handleRemove"
      :on-exceed="handleExceed"
      :on-success="handleSuccess"
      :on-error="handleError"
      :headers="UploadHeaders"
      :data="uploadData"
      :before-upload="beforeUpload"
      :on-preview="handlePreview"
      :show-file-list="false"
      drag
    >
      <template #default>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">拖拽文件到此处或 <em>点击上传</em></div>
      </template>
    </el-upload>

    <!-- 图片预览区域 -->
    <div v-if="previewUrl" class="preview-container">
      <h4>图片预览</h4>
      <img :src="previewUrl" class="preview-image" />
    </div>

    <!-- 图片预览弹窗 -->
    <el-dialog v-model="previewVisible" title="图片预览">
      <img :src="previewUrl" alt="Preview Image" style="width: 100%" />
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue"
import { ElMessage } from "element-plus"
import { getToken } from "@/utils/cache/cookies"
import { UploadFilled } from "@element-plus/icons-vue"

const props = defineProps({
  uploadType: {
    type: String,
    default: "buy"
  },
  apiEndpoint: {
    type: String,
    default: "/Ocr/recognizeGeneral"
  }
})

// Emits 定义返回事件
const emit = defineEmits(["upload-success", "upload-error", "upload-remove", "has-table-data"])

// 上传API地址
const apiUrl = import.meta.env.VITE_BASE_API + props.apiEndpoint
const UploadHeaders = {
  "X-Token": getToken()
}

// 上传数据对象，包含固定的type参数
const uploadData = {
  type: props.uploadType
}

// 上传文件列表
const fileList = ref<any[]>([])

// 当前预览图片的 URL
const previewUrl = ref("")
const previewVisible = ref(false)

// 删除图片
const handleRemove = () => {
  ElMessage.success("图片已删除")
  previewUrl.value = "" // 清空预览 URL
  emit("upload-remove")
}

// 上传成功
const handleSuccess = (response: any) => {
  ElMessage.success("图片上传成功")

  // 设置预览URL
  if (response.data && response.data.length > 0) {
    previewUrl.value = response.data[0].url
  }

  // 检查返回的数据是否包含表格数据
  if (response.code === 200 && response.data && response.data.data && response.data.data.length > 0) {
    // 如果包含表格数据，发送特殊的上传成功事件，表示需要直接跳转到步骤1
    emit("upload-success", response)
  } else {
    // 如果没有表格数据，只发送普通的上传成功事件
    emit("upload-success", response)
  }
}

// 上传失败
const handleError = (error: any, file: any, fileList: any[]) => {
  ElMessage.error("图片上传失败")
  // 从 fileList 中移除失败的文件
  const index = fileList.findIndex((item) => item.uid === file.uid)
  if (index !== -1) {
    fileList.splice(index, 1)
  }

  // 发送上传失败事件
  emit("upload-error", error)
}

// 上传前校验图片
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith("image/")
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error("上传文件必须是图片格式!")
    return false
  }
  if (!isLt5M) {
    ElMessage.error("上传图片大小不能超过 5MB!")
    return false
  }
  fileList.value = [file] // 只保留当前上传的文件
  return true
}

// 超出限制处理
const handleExceed = () => {
  ElMessage.warning("最多只能上传 1 张图片")
}

// 预览图片
const handlePreview = (file: any) => {
  previewUrl.value = file.url
  previewVisible.value = true
}

// 重置上传组件
const resetUploader = () => {
  fileList.value = [] // 清空文件列表
  previewUrl.value = "" // 清空预览 URL
}

// 暴露方法给父组件
defineExpose({ resetUploader })
</script>

<style scoped lang="scss">
.upload-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.image-uploader {
  text-align: center;
  width: 100%;
}

.el-upload {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}

:deep(.el-upload) {
  width: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
}
:deep(.el-upload-list) {
  width: 100%;
}

.el-upload-dragger {
  width: 100%;
  height: 180px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.el-icon--upload {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 10px;
}

.el-upload__text {
  color: #606266;
  font-size: 14px;
  text-align: center;
}

.el-upload__text em {
  color: #409eff;
  font-style: normal;
}

.preview-container {
  margin-top: 20px;
  text-align: center;
}

.preview-image {
  max-width: 100%;
  max-height: 300px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}
</style>
<style scoped>
/* 在 scoped 样式中使用 :deep 选择器穿透样式隔离 */
:deep(.el-upload.is-drag) {
  display: flex;
  width: 100%;
  height: 100%;
}
:deep(.el-upload--picture-card) {
  border: none;
}
:deep(.el-upload-dragger) {
  padding: 10px;
}
:deep(.el-upload-dragger.is-dragover) {
  padding: 10px;
}
</style>
